package com.jiuqi.bi.server.bsp.tagmanagement.excel;

import com.jiuqi.bi.runtime.bsp.exception.BSPException;
import com.jiuqi.bi.server.bsp.tagmanagement.model.TagItem;
import com.jiuqi.bi.util.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @ClassName: ExcelUtils
 * @Description: 标签导入导出工具
 * @author sunshuo
 * @date 2020年2月21日 下午3:40:10
 */
public class ExcelUtils {

    /**
     * 标识正则
     */
    public static final Pattern PATTERN_CODE = Pattern.compile("^[0-9a-zA-Z_]{0,}$");

    /**
     * 索引标题映射
     */
    private Map<Integer, String> indexTitleMap = new HashMap<Integer, String>();

    public static final String EXCEL_TITLE_TAGTITLE = "标签标题";
    public static final String EXCEL_TITLE_TAGCODE = "标签标识";
    public static final String EXCEL_TITLE_PARENTTAGTITLE = "上级标签标题";
    public static final String EXCEL_TITLE_PARENTTAGCODE = "上级标签标识";

    /**
     * 必要的标题列
     */
    public static final String[] EXCEL_TITLES_REQUIRE = {EXCEL_TITLE_TAGTITLE, EXCEL_TITLE_TAGCODE, EXCEL_TITLE_PARENTTAGCODE, EXCEL_TITLE_PARENTTAGTITLE};



    /**
     * 读取单元格的值
     * @param tagNode
     * @param rowIndex
     * @param cellIndex
     * @param cell
     * @throws BSPException
     */
    private void readCellValue(TagTreeNode tagNode, int rowIndex, int cellIndex, Cell cell, Set<String> errorMsgs) throws BSPException {
        String cellValue = cell.getStringCellValue();
        if(this.indexTitleMap.containsKey(cellIndex)) {
            String title = this.indexTitleMap.get(cellIndex);
            // 空校验
            boolean isRequireColumn = StringUtils.equals(EXCEL_TITLE_TAGCODE, title)
                    || StringUtils.equals(EXCEL_TITLE_TAGTITLE, title);
            if(isRequireColumn && StringUtils.isEmpty(cellValue.trim())) {
                StringBuilder errorMsg = new StringBuilder();
                buildEmptyErrorMsg(rowIndex, cellIndex, title, errorMsg);
                errorMsgs.add(errorMsg.toString());
            }
            if(StringUtils.equals(EXCEL_TITLE_TAGCODE, title)) {
                tagNode.setTagCode(cellValue.toUpperCase());
            } else if(StringUtils.equals(EXCEL_TITLE_TAGTITLE, title)) {
                tagNode.setTagTitle(cellValue);
            } else if(StringUtils.equals(EXCEL_TITLE_PARENTTAGCODE, title)) {
                tagNode.setParentTagCode(cellValue.toUpperCase());
            } else if(StringUtils.equals(EXCEL_TITLE_PARENTTAGTITLE, title)) {
                tagNode.setParentTagTitle(cellValue);
            }
            // 记录行列信息
            tagNode.setRowIndex(rowIndex + 1);
        }
    }
}
